<template>
    <div class="orders-container">
        <div class="header">
            <h1>我的回收订单</h1>
            <p class="slogan">让每一次回收，都是对环境的贡献</p>
        </div>
        
        <div class="orders-box">
            <!-- 订单状态切换 -->
            <div class="status-tabs">
                <el-radio-group v-model="currentStatus" @change="handleStatusChange">
                    <el-radio-button :label="0">全部订单</el-radio-button>
                    <el-radio-button :label="1">进行中</el-radio-button>
                    <el-radio-button :label="2">已完成</el-radio-button>
                    <el-radio-button :label="3">已取消</el-radio-button>
                </el-radio-group>
            </div>

            <!-- 订单列表 -->
            <div class="order-list" v-loading="loading">
                <template v-if="orders.length > 0">
                    <el-card v-for="order in orders" :key="order.recyclingOrderNum" class="order-card">
                        <div class="order-header">
                            <span class="order-num">订单号：{{ order.recyclingOrderNum }}</span>
                            <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
                        </div>
                        
                        <div class="order-content">
                            <div class="order-info">
                                <p><i class="el-icon-location"></i> 回收地址：{{ order.addressId }}</p>
                                <p><i class="el-icon-user"></i> 预约人：{{ order.appointName }}</p>
                                <p><i class="el-icon-mobile-phone"></i> 联系电话：{{ order.appointPhone }}</p>
                                <p><i class="el-icon-time"></i> 预约时间：{{ formatTime(order.appointmentTime) }}</p>
                                <p v-if="order.estimateWeight"><i class="el-icon-goods"></i> 预估重量：{{ order.estimateWeight }}kg</p>
                                <p v-if="order.remarks"><i class="el-icon-document"></i> 备注：{{ order.remarks }}</p>
                            </div>
                            
                            <div class="order-actions">
                                <!-- 根据订单状态显示不同按钮 -->
                                <template v-if="order.status === 1">
                                    <el-button 
                                        type="danger" 
                                        size="small" 
                                        @click="cancelOrder(order.recyclingOrderNum)"
                                    >取消订单</el-button>
                                </template>
                                <template v-if="order.status === 2">
                                    <el-button 
                                        type="success" 
                                        size="small" 
                                        @click="confirmOrder(order.recyclingOrderNum)"
                                    >确认完成</el-button>
                                </template>
                                <template v-if="![3, 4, 5].includes(order.status)">
                                    <el-button 
                                        type="primary" 
                                        size="small" 
                                        icon="el-icon-chat-dot-round"
                                        @click="enterChat(order.recyclingOrderNum)"
                                        :loading="chatLoading === order.recyclingOrderNum"
                                    >联系回收员</el-button>
                                </template>
                                <el-button 
                                    type="info" 
                                    size="small" 
                                    @click="viewOrderDetail(order)"
                                >查看详情</el-button>
                            </div>
                        </div>
                    </el-card>
                </template>
                
                <div v-else class="empty-orders">
                    <i class="el-icon-document"></i>
                    <p>暂无相关订单</p>
                </div>
            </div>
        </div>

        <!-- 订单详情对话框 -->
        <el-dialog 
            title="订单详情" 
            :visible.sync="dialogVisible"
            width="50%"
        >
            <div class="order-detail" v-if="currentOrder">
                <div class="detail-item">
                    <span class="label">订单编号：</span>
                    <span>{{ currentOrder.recyclingOrderNum }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">预约人：</span>
                    <span>{{ currentOrder.appointName }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">联系电话：</span>
                    <span>{{ currentOrder.appointPhone }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">回收地址：</span>
                    <span>{{ currentOrder.addressId }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">预约时间：</span>
                    <span>{{ formatTime(currentOrder.appointmentTime) }}</span>
                </div>
                <div class="detail-item" v-if="currentOrder.estimateWeight">
                    <span class="label">预估重量：</span>
                    <span>{{ currentOrder.estimateWeight }}kg</span>
                </div>
                <div class="detail-item">
                    <span class="label">订单状态：</span>
                    <el-tag :type="getStatusType(currentOrder.status)">
                        {{ getStatusText(currentOrder.status) }}
                    </el-tag>
                </div>
                <div class="detail-item" v-if="currentOrder.deliverName">
                    <span class="label">回收员：</span>
                    <span>{{ currentOrder.deliverName }}</span>
                </div>
                <div class="detail-item" v-if="currentOrder.deliverPhone">
                    <span class="label">回收员电话：</span>
                    <span>{{ currentOrder.deliverPhone }}</span>
                </div>
                <div class="detail-item" v-if="currentOrder.stationName">
                    <span class="label">回收站：</span>
                    <span>{{ currentOrder.stationName }}</span>
                </div>
                <div class="detail-item" v-if="currentOrder.remarks">
                    <span class="label">备注信息：</span>
                    <span>{{ currentOrder.remarks }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">创建时间：</span>
                    <span>{{ formatTime(currentOrder.createdAt) }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">更新时间：</span>
                    <span>{{ formatTime(currentOrder.updatedAt) }}</span>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
export default {
    name: 'UserOrders',
    data() {
        return {
            currentStatus: 0,
            orders: [],
            loading: false,
            dialogVisible: false,
            currentOrder: null,
            chatLoading: null
        }
    },
    mounted() {
        this.fetchOrders()
    },
    methods: {
        // 获取订单列表
        async fetchOrders() {
            this.loading = true
            try {
                const userId = localStorage.getItem('userId')
                if (!userId) {
                    this.$message.warning('请先登录')
                    this.$router.push('/login')
                    return
                }
                const data = new FormData()
                
                if (this.currentStatus === 0) {
                    data.append('userId', userId)
                    // 获取全部订单
                    const response = await this.$http.post('/recycle/recyclingOrder/selectAllOrderByUserId', data)
                    if (response.data.code === 200) {
                        this.orders = response.data.data
                    }
                } else if (this.currentStatus === 3) {
                    data.append('userId', userId)
                    data.append('status',3)
                    // 获取已取消订单
                    const response = await this.$http.post('/recycle/recyclingOrder/selectCancelOrderByUserId', data)
                    if (response.data.code === 200) {
                        this.orders = response.data.data
                    }
                }
            } catch (error) {
                this.$message.error('获取订单列表失败')
                console.error(error)
            } finally {
                this.loading = false
            }
        },

        // 取消订单
        async cancelOrder(orderNum) {
            try {
                await this.$confirm('确定要取消该订单吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                const data = new FormData()
                data.append('recyclingOrderNum', orderNum)
                const response = await this.$http.post('/recycle/recyclingOrder/cancelRecyclingOrder', data)
                
                if (response.data.code === 200) {
                    this.$message.success('订单取消成功')
                    this.fetchOrders()
                }
            } catch (error) {
                if (error !== 'cancel') {
                    this.$message.error('取消订单失败')
                    console.error(error)
                }
            }
        },

        // 确认订单
        async confirmOrder(orderNum) {
            try {
                const response = await this.$http.post('/recycle/recyclingOrder/confirmOrder', {
                    recyclingOrderNum: orderNum
                })
                
                if (response.data.code === 200) {
                    this.$message.success('订单确认成功')
                    this.fetchOrders()
                }
            } catch (error) {
                this.$message.error('确认订单失败')
                console.error(error)
            }
        },

        // 查看订单详情
        viewOrderDetail(order) {
            this.currentOrder = order
            this.dialogVisible = true
        },

        // 处理状态切换
        handleStatusChange() {
            this.fetchOrders()
        },

        // 格式化时间
        formatTime(time) {
            if (!time) return ''
            return new Date(time).toLocaleString()
        },

        // 获取状态文本
        getStatusText(status) {
            const statusMap = {
                       1: '待接单',
                2: '已接单',
                3: '已取消',
                4: '待评价',
                5: '已评价',
                6: '取件中',
            }
            return statusMap[status] || '未知状态'
        },

        // 获取状态标签类型
        getStatusType(status) {
            const typeMap = {
                1: 'warning',
                2: 'primary',
                3: 'danger',
                4: 'success'
            }
            return typeMap[status] || 'info'
        },

        // 进入聊天
        async enterChat(orderNum) {
            this.chatLoading = orderNum
            try {
                localStorage.setItem('currentChatOrder', orderNum)
                
                // 跳转到聊天页面
                this.$router.push({
                    path: '/user/chat',
                    query: { orderNum: orderNum }
                })
                
                this.$message.success('正在连接聊天...')
            } catch (error) {
                this.$message.error('进入聊天失败，请稍后再试')
                console.error('聊天连接错误:', error)
            } finally {
                this.chatLoading = null
            }
        }
    }
}
</script>

<style scoped>
.orders-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    min-height: 100vh;
    background-color: #f0f9eb;
}

.header {
    text-align: center;
    margin-bottom: 30px;
    padding: 20px 0;
}

.header h1 {
    color: #67c23a;
    font-size: 2.5em;
    margin-bottom: 10px;
}

.slogan {
    color: #606266;
    font-size: 1.2em;
    font-style: italic;
}

.orders-box {
    background: white;
    border-radius: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 30px;
}

.status-tabs {
    margin-bottom: 20px;
    text-align: center;
}

.order-card {
    margin-bottom: 20px;
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
}

.order-num {
    font-weight: bold;
    color: #303133;
}

.order-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
}

.order-info {
    flex: 1;
}

.order-info p {
    margin: 8px 0;
    color: #606266;
}

.order-info i {
    margin-right: 8px;
    color: #67c23a;
}

.order-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap; /* 在移动端自动换行 */
}

.el-button [class^="el-icon-"] {
    margin-right: 5px;
}

.empty-orders {
    text-align: center;
    padding: 40px 0;
    color: #909399;
}

.empty-orders i {
    font-size: 48px;
    margin-bottom: 10px;
}

.detail-item {
    margin-bottom: 15px;
}

.detail-item .label {
    font-weight: bold;
    color: #303133;
    margin-right: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .orders-container {
        padding: 10px;
    }

    .header h1 {
        font-size: 2em;
    }

    .orders-box {
        padding: 15px;
    }

    .order-content {
        flex-direction: column;
    }

    .order-actions {
        margin-top: 15px;
        justify-content: flex-end;
        width: 100%;
    }
    
    .order-actions .el-button {
        margin-bottom: 5px;
    }
}
</style> 
